package com.ruoyi.framework.interceptor;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.boc.config.HJConfig;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.JSONUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.util.BOCCryptography;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * SSOP单点登录拦截处理
 */
@Component
public class HJLogHandleInterceptor implements HandlerInterceptor {

    private final static Logger logger = LoggerFactory.getLogger(HJLogHandleInterceptor.class);

    @Resource
    private HJConfig hjConfig;

    @Resource
    private RedisCache redisCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("进入hj拦截器");
        String returnUrl = hjConfig.getReturnUrl();
        String appName = request.getParameter("appName");
        String bocTokenHj = request.getParameter("bocTokenHj");
        String deviceuuID = request.getParameter("deviceuuID");
        String username = request.getParameter("username");
        String ehrNo = request.getParameter("useraccount");
        System.out.println("appName:"+appName);
        System.out.println("bocTokenHj:"+bocTokenHj);
        System.out.println("deviceuuID:"+deviceuuID);
        System.out.println("username:"+username);
        System.out.println("ehrNo:"+ehrNo);
        //Map map = getUserCodeBySocket(deviceuuID,appName,bocTokenHj);
        //String ehrNo = map.get("ehrNo").toString();
        if (StringUtils.isEmpty(ehrNo)) {
            //接口请求失败
            System.out.println("HJ请求接口失败,ehrno为空");
            logger.error("HJ请求接口失败,ehrno为空");
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("code", 401);
            resultMap.put("msg", "ehrno为空");
            String json = JSONUtils.serialize(resultMap);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(json);
            response.flushBuffer();
            return false;
        } else {
            //需要重定向
            System.out.println("进入重定向");
//            Map<String, Object> resultMap = new HashMap<>();
//            resultMap.put("success", true);
//            resultMap.put("code", 10011);
//            resultMap.put("data", returnUrl+ "?ehrno=" + ehrno);
//            String json = JSONUtils.serialize(resultMap);
//            response.setContentType("application/json;charset=UTF-8");
//            response.getWriter().print(json);
//            response.flushBuffer();
            // 执行重定向
            String uuid = IdUtils.simpleUUID();
            CacheUtils.put(CacheConstants.SSOP_LOGIN,"hj_login_key"+uuid, ehrNo);
            response.sendRedirect(returnUrl+ "?ehrno=" + ehrNo+"&hjLoginKey="+"hj_login_key"+uuid);
            return false;
        }
    }

    /**
     * 根据行家app的token向总行P2环境进行认证并获取userCode（socket请求）
     * @param deviceuuID    设备ID
     * @param appName   系统名称
     * @param bocTokenHj    行家Token
     * @return
     */
    public Map getUserCodeBySocket(String deviceuuID, String appName, String bocTokenHj) throws JsonProcessingException {

//        String txnCode = hjConfig.getTxnCode();
//        String agentCode = hjConfig.getAgentCode();
//        String gatewayUrl = hjConfig.getGatewayUrl();
//        //组装请求报文
//        Map reqMap = new HashMap(), p2Map = new HashMap(), headerMap = new HashMap();
//        headerMap.put("txnCode", txnCode);
//        headerMap.put("agentCode", agentCode);
//        p2Map.put("apiCode","");
//        p2Map.put("langCode","zh_CN");
//        p2Map.put("chnlCode","01");
//        p2Map.put("equipmentId", deviceuuID);//设备ID
//        p2Map.put("systemName", appName);//产品系统名称
//        p2Map.put("accessToken", bocTokenHj);
//        p2Map.put("uuid", UUID.randomUUID().toString().replace("-",""));
//        reqMap.put("reqHeader", headerMap);
//        reqMap.put("reqBody", p2Map);
//        //String data = JsonUtils.object2Json(reqMap);
//        ObjectMapper objectMapper = new ObjectMapper();
//        String data = objectMapper.writeValueAsString(reqMap);
//        data = new DecimalFormat("00000").format(data.length()) + data;
//        //log.info("行家token向总行P2环境进行认证的请求报文: {}", data);
//        //System.out.println(data);
//        //调用Socket服务
//        String[] url = gatewayUrl.split(":");
//        String charset = "GBK";
//        Socket socket = null;
//        OutputStream out = null;
//        InputStream in = null;
//        StringBuffer result = new StringBuffer();
//        try {
//            socket = new Socket(url[0], Integer.parseInt(url[1]));
//            socket.setSoTimeout(30000);
//            out = socket.getOutputStream();
//            out.write(data.getBytes(charset));
//            socket.shutdownOutput();
//            in = socket.getInputStream();
//            int len;
//            byte[] bytes = new byte[1024];
//            while((len = in.read(bytes)) != -1){
//                result.append(new String(bytes, 0, len, charset));
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                if (in != null) in.close();
//                if (out != null) out.close();
//                if (socket != null) socket.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//
//        //解析返回报文
//        //log.info("行家token向总行P2环境进行认证的返回报文: {}", result.toString());
//        Map resultMap = new HashMap();
//        if(result.length()<5){
//            resultMap.put("retCode", "9999999");
//            resultMap.put("retMsg", "返回报文为空");  //返回信息
//            return resultMap;
//        }
//        JSONObject json = JSON.parseObject(result.toString().substring(5));
//        JSONObject respJson = json.getJSONObject("respHeader");
//        if(respJson.getString("apRetCode").equals("0000000")){  //成功
//            resultMap.put("retCode", "0000000");
//            JSONObject respBody = json.getJSONObject("respBody");
//            resultMap.put("userCode", respBody.getString("empeRefNo")); //员工编号
//            resultMap.put("orgCode", respBody.getString("instCode"));   //机构号
//        }else{  //失败
//            resultMap.put("retCode", "9999999");
//            resultMap.put("retMsg", respJson.getString("apRetMsg"));    //返回信息
//        }
//        return  resultMap;
        Map map = new HashMap();
        map.put("ehrNo","admin");
        return map;
    }
}

